﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Builder;
using GuanQL.Core.Stores;
using GuanQL.Core.Domain.Accounts;
using GuanQL.Core;

namespace GanQL.Web.Infrastructure.Infrastructure
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddEfCore(this IServiceCollection services, IHostingEnvironment env, IConfiguration configuration)
        {
            services.AddEntityFramework()
              .AddDbContext<GQLDbContext>(option =>
              {
                  option.UseSqlServer(configuration.GetConnectionString("GuanQL"), o => o.MigrationsAssembly("GuanQL.Web"));
              });
            return services;
        }

        public static IServiceCollection AddCustomizedIdentity(this IServiceCollection services)
        {
            services.AddIdentity<User, Role>(configure => { configure.Cookies.ApplicationCookie.LoginPath = "/login"; })
                .AddRoleStore<GQLRoleStore>()
                .AddUserStore<GQLUserStore>()
                .AddDefaultTokenProviders();
            return services;
        }

        public static IServiceCollection ConfigureOptions(this IServiceCollection services, IConfiguration config)
        {
            services.AddOptions();
            var secretKey = "zhongjiasecret_secretkey!zj";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            services.Configure<TokenProviderOptions>(option =>
            {
                option.Audience = "TransmitterAudience";
                option.Issuer = "TransmitterIssuer";
                option.SigningKey = signingKey;
                option.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            });
            services.Configure<IdentityOptions>(options =>
            {
                options.User.AllowedUserNameCharacters = null;
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
            });

            services.Configure<AppSettings>(config.GetSection("AppSettings"));
            services.AddScoped(cfg => cfg.GetService<IOptionsSnapshot<AppSettings>>().Value);
            services.AddSingleton(config);
            return services;
        }
    }
}
